from tortoise import fields, models


class OperationLogModel(models.Model):
    """操作日志模型"""
    
    id = fields.IntField(pk=True)
    user_id = fields.IntField(description="操作用户ID")
    username = fields.CharField(max_length=50, description="操作用户名")
    module = fields.CharField(max_length=50, description="操作模块")
    action = fields.CharField(max_length=50, description="操作动作")
    method = fields.CharField(max_length=10, description="HTTP方法")
    path = fields.CharField(max_length=255, description="请求路径")
    ip = fields.CharField(max_length=50, description="IP地址")
    user_agent = fields.CharField(max_length=500, null=True, description="用户代理")
    request_data = fields.JSONField(null=True, description="请求数据")
    response_data = fields.JSONField(null=True, description="响应数据")
    status_code = fields.IntField(description="状态码")
    duration = fields.FloatField(description="执行时长(秒)")
    success = fields.BooleanField(description="是否成功")
    error_message = fields.TextField(null=True, description="错误信息")
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")

    class Meta:
        table = "operation_logs"
        table_description = "操作日志表"

    def __str__(self):
        return f"{self.username} - {self.module}.{self.action}"

    @classmethod
    async def create_log(
        cls,
        user_id: int,
        username: str,
        module: str,
        action: str,
        method: str,
        path: str,
        ip: str,
        status_code: int,
        duration: float,
        success: bool,
        user_agent: str = None,
        request_data: dict = None,
        response_data: dict = None,
        error_message: str = None
    ):
        """创建操作日志"""
        return await cls.create(
            user_id=user_id,
            username=username,
            module=module,
            action=action,
            method=method,
            path=path,
            ip=ip,
            user_agent=user_agent,
            request_data=request_data,
            response_data=response_data,
            status_code=status_code,
            duration=duration,
            success=success,
            error_message=error_message
        )

    @classmethod
    async def get_user_logs(cls, user_id: int, limit: int = 50):
        """获取用户操作日志"""
        return await cls.filter(user_id=user_id).order_by('-created_at').limit(limit)

    @classmethod
    async def get_module_logs(cls, module: str, limit: int = 50):
        """获取模块操作日志"""
        return await cls.filter(module=module).order_by('-created_at').limit(limit)

    @classmethod
    async def get_error_logs(cls, limit: int = 50):
        """获取错误日志"""
        return await cls.filter(success=False).order_by('-created_at').limit(limit) 